// try {
//   self.importScripts('cache.js')
//   // success get CACHE
//   console.log('success load cache list')
// } catch (exp) {
//   console.log('no cache.js')
//   var CACHE = []
// }
var CACHE = []

var appShellFiles = [
  '/'
]
var cacheName = 'ummeeting2-store'
var contentToCache = appShellFiles.concat(CACHE)
var contentFetchFirst = [
  '/sw.js',
]

self.addEventListener('install', function (e) {
  console.log('SW: service worker is installed!')
  // e.waitUntil(
  //   caches.open(cacheName).then(function (cache) {
  //     return cache.addAll(contentToCache)
  //   })
  // )
})

self.addEventListener('fetch', function (e) {
  // console.log('SW: fetch ', e.request.url)
  let url = new URL(e.request.url)

  // pass resources NOT includes in 'contentToCache' list
  // if (!contentToCache.find(item => url.pathname === item)) return

  // pass resources includes in 'contentFetchFirst' list
  if (contentFetchFirst.find(item => url.pathname === item)) return

  // pass resource NOT GET method
  if (e.request.method !== 'GET') return

  e.respondWith(async function () {
    // Try to get the response from a cache.
    const cache = await caches.open(cacheName)
    const cachedResponse = await cache.match(e.request)

    // Cache first
    e.waitUntil(cache.add(e.request))
    if (cachedResponse) {
      // If we found a match in the cache, return it, but also
      // update the entry in the cache in the background.
      return cachedResponse
    }
    // If we didn't find a match in the cache, use the network.
    return fetch(e.request)
  }())
})

self.addEventListener('activate', (event) => {
  console.log('SW: activate event.')
  event.waitUntil(
    caches.keys().then((keyList) => {
      return Promise.all(keyList.map((key) => {
        // if (cacheName !== key) {
        // Service Workder更新后，清空缓存
        console.log('SW: delete', key)
        return caches.delete(key)
        // }
      }))
    })
  )
})